<template>
    <div class="using-trajectory-content">
        <!-- 筛选项 -->
        <div class="screening">
            <el-row class="device-data_row device-data_row--filter" type="flex">
                <el-select class="filter-item" clearable filterable @change="screeningChange"
                           v-model="paramsDft.apptype"
                           placeholder="品类">
                    <el-option
                            v-for="{ value, label } in categorySelect"
                            :key="value"
                            :label="label"
                            :value="value">
                    </el-option>
                </el-select>
                <el-select class="filter-item" clearable filterable @change="screeningChange"
                           v-model="paramsDft.sn8" placeholder="型号">
                    <el-option
                            v-for="item in sN8List"
                            :key="item"
                            :label="item"
                            :value="item">
                    </el-option>
                </el-select>
                <el-select class="filter-item" @change="_provinceChange" clearable filterable
                           v-model="paramsDft.province_name"
                           placeholder="省">
                    <el-option
                            v-for="item in provinceList"
                            :key="item"
                            :label="item"
                            :value="item">
                    </el-option>
                </el-select>
                <el-select class="filter-item" clearable filterable @change="screeningChange"
                           v-model="paramsDft.city_name" placeholder="市">
                    <el-option
                            v-for="item in cityListByProvince"
                            :key="item"
                            :label="item"
                            :value="item">
                    </el-option>
                </el-select>
                <!--<el-select class="filter-item" disabled filterable v-model="paramsDft.apptype" placeholder="对比">-->
                <!--<el-option-->
                <!--v-for="{ value, label } in categorySelect"-->
                <!--:key="value"-->
                <!--:label="label"-->
                <!--:value="value">-->
                <!--</el-option>-->
                <!--</el-select>-->
            </el-row>
            <el-row class="device-data_row device-data_row--filter">
                <el-radio-group @change="timeRadioChange" v-model="paramsDft.timeType">
                    <el-radio label="1" border>当天</el-radio>
                    <el-radio label="2" border>近7天</el-radio>
                    <el-radio label="3" border>近30天</el-radio>
                    <el-radio label="4" border>自定义</el-radio>
                </el-radio-group>
                <el-date-picker
                        style="margin-left: 15px"
                        v-if="paramsDft.timeType == '4'"
                        class="filter-item"
                        v-model="paramsDft.dateRange"
                        type="daterange"
                        @change="dataPickerChange"
                        range-separator="至"
                        value-format="yyyy-MM-dd"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                </el-date-picker>
            </el-row>
            <el-row style="margin-top: 20px" class="device-data_row device-data_row--filter">
                <el-col :span="5">
                    <div class="search">
                        <el-input
                                placeholder="搜索"
                                v-model.trim="paramsDft.user_account"
                                prefix-icon="el-icon-search"
                                @clear="_initPage"
                                clearable>
                        </el-input>
                    </div>
                </el-col>
                <el-col :span="4" style="margin-left: 20px">
                    <el-radio-group @change="originalTypeChange" v-model="paramsDft.originalType">
                        <el-radio label="1" border>插件</el-radio>
                        <el-radio label="2" border>设备</el-radio>
                    </el-radio-group>
                </el-col>
                <el-col :span="2">
                    <el-button type="primary" class="search-btn" @click="_initPage"
                               :loading="modeLoading.pluginUsageTrack">查询
                    </el-button>
                </el-col>
            </el-row>
        </div>

        <div class="content-list" v-loading="modeLoading.pluginUsageTrack">
            <el-row>
                <!--<el-col :span="6">-->
                <!--<div class="left">-->
                <!--<div class="title">用户信息</div>-->
                <!--<div class="info-list">-->
                <!--<div class="info-ietm">-->
                <!--<span>用户名：</span>-->
                <!--<span></span>-->
                <!--</div>-->
                <!--<div class="info-ietm">-->
                <!--<span>性别：</span>-->
                <!--<span></span>-->
                <!--</div>-->
                <!--<div class="info-ietm">-->
                <!--<span>用户名：</span>-->
                <!--<span></span>-->
                <!--</div>-->
                <!--</div>-->
                <!--</div>-->
                <!--</el-col>-->
                <el-col :span="24">
                    <div class="right">
                        <div class="onload-box">
                            <div class="title">使用轨迹</div>
                            <el-button type="primary" class="search-btn" @click="_onloadFileFunType"
                                       :loading="modeLoading.onloadFile">下载
                            </el-button>
                        </div>
                        <el-table
                                :data="tableListDataMap.pluginUsageTrack"
                                stripe
                                v-if="paramsDft.originalType == '1'"
                                height="400"
                                style="width: 100%">
                            <el-table-column width="120" prop="action_time" sortable label="时间"></el-table-column>
                            <el-table-column width="120" prop="appliance_id" sortable label="APPID"></el-table-column>
                            <el-table-column width="120" prop="user_account" sortable label="用户名"></el-table-column>
                            <el-table-column width="120" prop="apptype" sortable label="品类"></el-table-column>
                            <el-table-column width="120" prop="sn8" sortable label="sn8"></el-table-column>
                            <el-table-column width="120" prop="province_name" sortable label="省份"></el-table-column>
                            <el-table-column width="120" prop="city_name" sortable label="城市"></el-table-column>
                            <el-table-column width="120" prop="page_name" sortable label="当前页"></el-table-column>
                            <el-table-column width="120" prop="sub_action" sortable label="行为"></el-table-column>
                            <el-table-column width="120" prop="action_result" sortable label="结果"></el-table-column>
                        </el-table>
                        <el-table
                                :data="tableListDataMap.pluginUsageTrack"
                                stripe
                                v-if="paramsDft.originalType == '2'"
                                height="400"
                                style="width: 100%">
                            <el-table-column width="120" prop="time" sortable label="时间"></el-table-column>
                            <el-table-column width="120" prop="appliance_id" sortable label="APPID"></el-table-column>
                            <el-table-column width="120" prop="runmode" sortable label="运行模式"></el-table-column>
                            <el-table-column width="120" prop="runstatus" sortable label="运行状态"></el-table-column>
                            <el-table-column width="120" prop="apptype" sortable label="品类"></el-table-column>
                            <el-table-column width="120" prop="sn8" sortable label="sn8"></el-table-column>
                            <el-table-column width="120" prop="province_name" sortable label="省份"></el-table-column>
                            <el-table-column width="120" prop="city_name" sortable label="城市"></el-table-column>
                            <el-table-column width="150" prop="worktimehour" sortable label="工作时间（时）"></el-table-column>
                            <el-table-column width="150" prop="worktimemin" sortable label="工作时间（分）"></el-table-column>
                            <el-table-column width="150" prop="worktimesec" sortable label="工作时间（秒）"></el-table-column>
                            <el-table-column width="120" prop="cloudymenuid" sortable label="菜单ID"></el-table-column>
                            <el-table-column width="120" prop="door_open" sortable label="炉门状态"></el-table-column>
                            <el-table-column width="120" prop="fire_power" sortable label="火力"></el-table-column>
                            <el-table-column width="120" prop="error_type" sortable label="故障码"></el-table-column>
                        </el-table>
                        <el-pagination
                                background
                                layout="total, prev, pager, next"
                                :current-page.sync="paramsDft.page"
                                :page-size="1000"
                                @current-change="currentPageChange"
                                :total="total">
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>

        </div>
    </div>
</template>

<script>
import commonMixin from '@/mixins/common'
import { categorySelect } from '@/utils/consts'
import moment from 'moment'

export default {
  mixins: [commonMixin],
  created () {
  },
  data () {
    return {
      total: 0,
      sN8model_type: '',
      categoryValue: '',
      categorySelect: categorySelect, // 品类
      provinceList: [],
      cityListByProvince: [],
      sN8List: [],
      menuList: [],
      modeNameList: [],
      paramsDft: {
        page: 1,
        timeType: '2',
        dateRange: '',
        model_type: '', // 型号
        province_name: '', // 省份
        city_name: '', // 城市
        apptype: '', // 品类
        sn8: '', // sn8
        user_account: '', // 用户账户
        originalType: '1',
        start_day: moment().add('-7', 'days').format('YYYY-MM-DD'), // 开始日期
        end_day: moment(new Date()).format('YYYY-MM-DD')// 结束日期
      },
      modeLoading: {
        pluginUsageTrack: false,
        onloadFile: false
      },
      tableListDataMap: {
        pluginUsageTrack: []
      }
    }
  },
  mounted () {
    // 获取省份
    this._getProvinceList()
    // 获取sn8
    this._getSN8List()
    // 获取菜单
    this._getMenuList()
    this._initPage()
  },
  methods: {
    _initPage () {
      // this._getPluginUsageTrack()

      if (this.paramsDft.originalType === '1') {
        // 插件
        this._getPluginOriginalData()
      } else {
        // 设备
        this._getDeviceOriginalData()
      }
    },
    dataPickerChange (time) {
      if (this.paramsDft.timeType === '4') {
        this.paramsDft.start_day = time[0]
        this.paramsDft.end_day = time[1]
        this.screeningChange()
      }
    },
    /**
             * 筛选项更改
             * @returns {Promise<void>}
             * @private
             */
    screeningChange () {
      this._initPage()
    },
    timeRadioChange () {
      let timeMap = {
        // 当日
        'time-1': {
          start_day: moment(new Date()).format('YYYY-MM-DD'),
          end_day: moment(new Date()).format('YYYY-MM-DD')
        },
        // 近7天
        'time-2': {
          start_day: moment().add('-7', 'days').format('YYYY-MM-DD'),
          end_day: moment(new Date()).format('YYYY-MM-DD')
        },
        // 近30天
        'time-3': {
          start_day: moment().add('-30', 'days').format('YYYY-MM-DD'),
          end_day: moment(new Date()).format('YYYY-MM-DD')
        }
      }
      if (this.paramsDft.timeType === '4') {
        return
      }
      this.paramsDft.start_day = timeMap['time-' + this.paramsDft.timeType].start_day
      this.paramsDft.end_day = timeMap['time-' + this.paramsDft.timeType].end_day
      this.screeningChange()
    },
    /**
             * 获取省份
             * @returns {Promise<void>}
             * @private
             */
    async _getProvinceList () {
      let { data: res } = await this.$http.get(this.getApiUrl('dataanalysis/common/getProvinceList', false))
      if (res.code === 0) {
        this.provinceList = res.data
      }
    },
    _provinceChange (e) {
      if (e) {
        this._initPage()
        this._getCityListByProvince(e)
      }
    },
    /**
             * 获取市
             * @returns {Promise<void>}
             * @private
             */
    async _getCityListByProvince (city) {
      let { data: res } = await
      this.$http.get(this.getApiUrl(`dataanalysis/common/getCityListByProvince?province_name=${city}`, false))
      if (res.code === 0) {
        this.cityListByProvince = res.data
      }
    },
    /**
             * 获取sn8
             * @returns {Promise<void>}
             * @private
             */
    async _getSN8List () {
      let { data: res } = await
      this.$http.get(this.getApiUrl(`dataanalysis/common/getSN8List`, false))
      if (res.code === 0) {
        this.sN8List = res.data
      }
    },
    /**
             * 获取菜单
             * @returns {Promise<void>}
             * @private
             */
    async _getMenuList () {
      let { data: res } = await
      this.$http.get(this.getApiUrl(`/dataanalysis/common/getMenuList`, false))
      if (res.code === 0) {
        this.menuList = res.data
      }
    },
    paramsFilter (paramsArr) {
      let params = {}
      this._.each(paramsArr, (item) => {
        if (this.paramsDft[item]) {
          params[item] = this.paramsDft[item]
        }
      })
      return params
    },
    currentPageChange () {
      if (this.paramsDft.originalType === '1') {
        // 插件
        this._getPluginOriginalData()
      } else {
        // 设备
        this._getDeviceOriginalData()
      }
    },
    originalTypeChange (e) {
      if (e === '1') {
        // 插件
        this._getPluginOriginalData()
      } else {
        // 设备
        this._getDeviceOriginalData()
      }
    },
    /*
                       * 插件
                       */
    async _getPluginOriginalData () {
      let paramsArr = ['province_name', 'city_name', 'apptype', 'sn8', 'user_account', 'start_day', 'end_day', 'page']
      let params = this.paramsFilter(paramsArr)
      this.modeLoading.pluginUsageTrack = true
      let { data: res } = await this.$http.get(this.getApiUrl(`dataanalysis_iot/usagetrack/getPluginOriginalData`, false),
        { params: params })
      if (res.code === 0) {
        this.tableListDataMap.pluginUsageTrack = res.data.list
        this.total = res.data.total
      }
      this.modeLoading.pluginUsageTrack = false
    },
    /*
                       * 设备
                       */
    async _getDeviceOriginalData () {
      let paramsArr = ['province_name', 'city_name', 'apptype', 'sn8', 'user_account', 'start_day', 'end_day', 'page']
      let params = this.paramsFilter(paramsArr)
      this.modeLoading.pluginUsageTrack = true
      let { data: res } = await this.$http.get(this.getApiUrl(`dataanalysis_iot/usagetrack/getDeviceOriginalData`, false),
        { params: params })
      if (res.code === 0) {
        this.tableListDataMap.pluginUsageTrack = res.data.list
        this.total = res.data.total
      }
      this.modeLoading.pluginUsageTrack = false
    },
    /*
                      * 插件下载
                      */
    _onloadFileFunType () {
      if (this.paramsDft.originalType === '1') {
        this._onloadFileFun('dataanalysis_iot/usagetrack/getPluginOriginalDataFile')
      } else {
        this._onloadFileFun('dataanalysis_iot/usagetrack/getDeviceOriginalDataFile')
      }
    },
    async _getPluginUsageTrack () {
      let paramsArr = ['province_name', 'city_name', 'apptype', 'sn8', 'user_account', 'start_day', 'end_day', 'page']
      let params = this.paramsFilter(paramsArr)
      this.modeLoading.pluginUsageTrack = true
      let { data: res } = await this.$http.get(this.getApiUrl(`dataanalysis_iot/usagetrack/getPluginUsageTrack`, false),
        { params: params })
      if (res.code === 0) {
        this.tableListDataMap.pluginUsageTrack = res.data.actionList
        this.total = res.data.total
      }
      this.modeLoading.pluginUsageTrack = false
    },
    async _onloadFileFun (url) {
      let paramsArr = ['province_name', 'city_name', 'apptype', 'sn8', 'user_account', 'start_day', 'end_day']
      let params = this.paramsFilter(paramsArr)
      let name = this.paramsDft.originalType === '1' ? '插件' : '设备'
      this.modeLoading.onloadFile = true
      let data = await this.$http.get(this.getApiUrl(url, false),
        {
          params: params,
          headers: { 'Content-Type': 'application/json,charset=utf-8' },
          responseType: 'arraybuffer'
        })
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(new Blob([data.data], { type: 'application/vnd.ms-excel,charset=utf-8' }))
      link.target = '_blank'
      link.download = name + '-使用轨迹.xls'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      this.modeLoading.onloadFile = false
    }
  }
}
</script>

<style lang="scss" scoped>
    @import "~element-theme-chalk/src/common/var.scss";
    @import "@/assets/scss/modules/variables-module.scss";
    @import "@/assets/scss/modules/common-module.scss";
    .using-trajectory-content {
        .search {
            display: flex;
            justify-content: flex-start;
            align-items: center;
        }
        .onload-box {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 20px;
        }
        .search-btn {
            background-color: #5768F3;
            border-color: #5768F3;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: 15px;
            padding: 8px 15px;
            color: #ffffff;
            height: 40px;
            width: 60px;
            border-radius: 4px;
            cursor: pointer;
        }
        .content-list {
            margin-top: 20px;
            background: rgba(255, 255, 255, 1);
            box-shadow: 0px 4px 16px 0px rgba(167, 175, 183, 0.33), 0px 0px 0px 0px rgba(90, 113, 208, 0.11);
            border: 1px solid rgba(221, 228, 235, 1);
            padding: 15px;
            .title {
                color: #212529;
                font-size: 20px;
                margin-bottom: 20px;
            }
            .info-ietm {
                margin-bottom: 10px;
            }
        }
    }
    .device-data_row {
        & ~ .device-data_row {
            margin-top: $gap-big;
        }
        .box-card {
            & + .box-card {
                margin-top: 0;
                margin-left: $gap-default;
            }
            .title {
                font-weight: bolder;
                font-size: 145%;
            }
        }
    }
    .device-data_row--filter {
        .filter-item {
            ::v-deep .el-input {
                @include el-input__grey;
            }
            &.el-date-editor {
                ::v-deep {
                    @include el-date-editor__grey;
                }
            }
            &:not(.el-date-editor) {
                width: 8em;
            }
            & ~ .filter-item {
                margin-left: $gap-default;
            }
        }
        .el-checkbox, .el-radio {
            margin-right: 0;
            @include el-date-editor__grey
        }
    }
    .device-data_row--survey {
        .box-card {
            .radio_data-range {
                ::v-deep .el-radio-button {
                    & ~ .el-radio-button {
                        margin-left: $gap-default;
                    }
                    .el-radio-button__inner {
                        border: none;
                    }
                    .el-radio-button__orig-radio:checked + .el-radio-button__inner {
                        color: $input-font-color;
                        background-color: $input-background-color;
                        box-shadow: none;
                    }
                }
            }
            .card-content {
                .data-item {
                    flex: auto;
                    &:not(:last-of-type) {
                        padding-right: 30px;
                    }
                    & ~ .data-item {
                        padding-left: 30px;
                        border-left: 1px solid $--border-color-base;
                    }
                    .item-row {
                        & ~ .item-row {
                            margin-top: $gap-small;
                        }
                    }
                    .num {
                        font-size: 150%;
                        font-weight: bolder;
                        color: $--color-primary;
                    }
                    .label {
                        font-size: 95%;
                        color: $--color-info;
                    }
                    .trend {
                        font-weight: bold;
                        .range {
                            font-weight: normal;
                            color: $--color-primary-light-1;
                        }
                    }
                }
            }
        }
    }
    .device-data_row--stage-trend {
    }
    .device-data_row--ratio {
        .box-card {
            flex: 1 1 50%;
        }
    }
    .device-data_row--retention {
        .index-btn-group {
            ::v-deep {
                .label {
                    @include style__grey;
                }

                .el-date-editor {
                    @include el-date-editor__grey;
                }
            }
        }
    }
</style>
